/*  
 * i-OSGi - Tunable Bundle Isolation for OSGi
 * Copyright (C) 2011  Sven Schulz
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.iosgi.outpost.util.ipr;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.SocketException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Sven Schulz
 */
public class Announcer {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(Announcer.class);

	private final DatagramSocket socket;

	public Announcer() throws SocketException {
		socket = new DatagramSocket();
	}

	public void announce() throws IOException {
		Map<MacAddress, InterfaceAddress> addrs = MacAddress.getAddresses();
		IPRPacket iprp = new IPRPacket();
		for (Map.Entry<MacAddress, InterfaceAddress> e : addrs.entrySet()) {
			iprp.add(e.getKey(), e.getValue().getAddress());
		}
		for (InterfaceAddress addr : addrs.values()) {
			DatagramPacket dp = iprp.toDatagram();
			byte[] rawbc = addr.getAddress().getAddress();
			/*
			 * TODO Bug: addr.getNetworkPrefixLength() returns 128 for IPv4
			 * addresses.
			 */
			int npl = 24 / 8;
			for (int i = npl; i <= 3; i++) {
				rawbc[i] = -1;
			}
			InetAddress bcaddr = InetAddress.getByAddress(rawbc);
			dp.setAddress(bcaddr);
			dp.setPort(2505);
			LOGGER.debug("announcing {} on {}:{}",
					new Object[] { addrs, dp.getAddress(), dp.getPort() });
			socket.send(dp);
		}
	}

	public void announce(int count, long delay, TimeUnit unit)
			throws IOException, InterruptedException {
		for (int i = 0; i < count; i++) {
			announce();
			unit.sleep(delay);
		}
	}

}